import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
import all from '@/lib/page'
Vue.use(Router)

const router = new Router({
  routes: [
    ...all.routes
  ]
})

router.beforeEach((to, from, next) => {
  const auth = typeof to.meta.auth !== 'undefined' ? to.meta.auth : true
  // const name = typeof to.meta.name !== 'undefined' ? to.meta.name : to.name
  if (!auth) {
    next()
    return
  }
  if (!store.state.user.isLogin) {
    if (to.name !== 'login') {
      store.commit('user/setLoginRedirect', to)
    } else {
      store.commit('user/setLoginRedirect', false)
    }
    next({ path: '/login' })
    return
  }
  // 判断是否有权限 @todo
  // 判断页面是否存在
  if (!to.matched.length) {
    next({ path: '/404' })
    return
  }
  next()
})

export default router
